# _*_ coding utf-8 _*_
# FILENAME：requireSummaryList.py
# DESCRIPTION: 需求汇总管理
# AUTH: jarvis zhang
# DATE: 2022/5/3110:53 上午
import datetime
import threading

import openpyxl
from PyQt5 import QtGui
from PyQt5.QtWidgets import *
from PyQt5.Qt import *
from sqlalchemy import desc, or_
import qtawesome as qta
from components.BaseQueryWindow import BaseQueryWindow, CustomButtonDelegate
from components.MessageBoxComponent import MessageBox
from constant import DownloadType
from models.baseModel import get_session, delete
from models.factoryModel import FactoryModel
from models.requireModel import RequireDetailsModel, RequireModel
from models.requireSummaryModel import RequireSummaryModel
from utils.logUtils import DownloadLog
from views.log.downloadHandleLogView import DownloadHandleLogWindow
from views.requiresummary.requireSummaryDetailList import RequireSummaryDetailList
from views.requiresummary.summaryForm import SummaryForm
from views.requiresummary.uploadDialog import UploadDialog
from views.requiresummary.versionDialog import VersionDialog


class RequireSummaryList(BaseQueryWindow):
    def __init__(self):
        super(RequireSummaryList, self).__init__()
        self.__init_ui()

    ''' UI '''

    def __init_ui(self):
        # 隐藏上传日志、运算日志按钮
        self.toolBar.actions()[1].setVisible(False)
        self.toolBar.actions()[2].setVisible(False)

        # 信号槽连接
        self.btn_add.clicked.connect(self.add_click)
        self.btn_close.clicked.connect(self.close)
        self.btn_download_log.clicked.connect(self.download_log_click)
        self.btn_refresh.clicked.connect(self.refresh)

    ''' Methods '''

    #  窗体show
    def show(self):
        super(RequireSummaryList, self).show()
        self.setWindowTitle("零件需求汇总管理")
        # 设置表头
        self.setTableViewHeaders()
        # 查询
        total = self.query_total(self.edit_vension.text())
        self.setTotalRecordCount(total)  # 总量
        self.recordQuery(0)  # page

        # 关闭窗体,释放资源

    def close(self):
        super(RequireSummaryList, self).close()

    def setTableViewHeaders(self):
        self.tableeHeaderLabels = ['编号', '版本名称', '所属工厂', '创建时间', '更新时间', '操作', '参与运算的焊装零件版本编号', '参与运算的涂装零件版本编号',
                                   '参与运算的总装零件版本编号', '工厂版本编号']
        self.dataModel.setHorizontalHeaderLabels(self.tableeHeaderLabels)
        # 隐藏列
        self.tableView.setColumnHidden(6, True)
        # 设置列宽
        self.tableView.setColumnWidth(0, 50)
        self.tableView.setColumnWidth(1, 350)
        self.tableView.setColumnWidth(2, 120)
        self.tableView.setColumnWidth(3, 150)
        self.tableView.setColumnWidth(4, 150)
        self.tableView.setColumnWidth(5, 250)
        self.tableView.setColumnWidth(6, 250)
        self.tableView.setColumnWidth(7, 250)
        self.tableView.setColumnWidth(8, 250)
        self.tableView.setColumnWidth(9, 250)
        # 隐藏按钮
        self.tableView.setColumnHidden(6, True)
        self.tableView.setColumnHidden(7, True)
        self.tableView.setColumnHidden(8, True)
        self.tableView.setColumnHidden(9, True)
        #  设置代理按钮,[btnEdit, btnUpload, btnCal, btnView, btnDel, btnDownload]
        delegateBtnIsHiddes = [False, True, False, False, False, False]
        self.tableView.setItemDelegateForColumn(5, CustomButtonDelegate(self, delegateBtnIsHiddes))

    # 刷新
    def refresh(self):
        # 查询
        total = self.query_total(self.edit_vension.text())
        self.setTotalRecordCount(total)  # 总量
        self.recordQuery(0)  # page

    # 记录查询，重写
    def recordQuery(self, limitIndex):
        data = self.page(limitIndex, self.PageRecordCount, self.edit_no.text(), self.edit_vension.text())
        self.dataModel.clear()
        if len(data) > 0:
            for i in range(len(data)):
                # 添加
                newItem = QStandardItem(str(data[i][0].id))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 0, newItem)

                newItem = QStandardItem(str(data[i][0].version_name))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 1, newItem)

                newItem = QStandardItem(str(data[i][1].name))  # 工厂名称
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 2, newItem)

                newItem = QStandardItem(str(data[i][0].create_date))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 3, newItem)

                newItem = QStandardItem(str(data[i][0].update_date))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 4, newItem)

                newItem = QStandardItem("")
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 5, newItem)

                newItem = QStandardItem(str(data[i][0].weld_version_id))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 6, newItem)

                newItem = QStandardItem(str(data[i][0].paint_version_id))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 7, newItem)

                newItem = QStandardItem(str(data[i][0].summary_version_id))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 8, newItem)

                newItem = QStandardItem(str(data[i][0].factory_id))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                self.dataModel.setItem(i, 9, newItem)
        self.setTableViewHeaders()

    # 分页查询列表
    def page(self, limitIndex=0, pageRecordCount=0, no=0, version=None):
        # 获取dbsession
        session = get_session()
        # 拼接查询
        my_query = session.query(RequireSummaryModel, FactoryModel) \
            .join(FactoryModel, FactoryModel.id == RequireSummaryModel.factory_id)
        my_query = my_query.filter(RequireSummaryModel.is_del == 0)
        # 拼接查询条件
        if version != "":
            my_query = my_query.filter(RequireSummaryModel.version_name.like("%" + version + "%"))
        if no != "":
            my_query = my_query.filter(RequireSummaryModel.id == no)
        # 拼接排序条件
        my_query = my_query.order_by(desc(RequireSummaryModel.update_date))
        # 分页
        my_query = my_query.offset(limitIndex).limit(pageRecordCount)
        # 执行查询
        model = my_query.all()
        session.close()
        return model

    # 查询数据总量
    def query_total(self, version=None, factory=None):
        # 获取dbsession
        session = get_session()
        # 拼接查询
        my_query = session.query(RequireSummaryModel, FactoryModel) \
            .join(FactoryModel, FactoryModel.id == RequireSummaryModel.factory_id)
        my_query = my_query.filter(RequireSummaryModel.is_del == 0)
        # 拼接查询条件
        if version:
            my_query = my_query.filter(RequireSummaryModel.version_name == version)
        if factory:
            my_query = my_query.filter(RequireSummaryModel.factory_id == factory)
        # 执行查询
        count = my_query.count()
        session.close()
        return count

    # 新增
    def add_click(self):
        VersionDialog.get_dialog(self)

    # 下载日志
    def download_log_click(self):
        self.download_log = DownloadHandleLogWindow(type=DownloadType.REQUIRE_SUMMARY.value)
        self.download_log.show()

    # 编辑，继承父类
    def edit_click(self):
        super(RequireSummaryList, self).edit_click()
        button = self.sender()
        if button:
            cell = button.index
            row = cell[0]
            id = self.dataModel.item(row, 0).text()
            VersionDialog.get_dialog(self, int(id))

    #  上传，继承父类
    def upload_click(self):
        button = self.sender()
        if button:
            cell = button.index
            row = cell[0]
            id = self.dataModel.item(row, 0).text()
            UploadDialog.get_dialog(self, id)
            print(row)

    #  汇总事件
    def cal_click(self):
        button = self.sender()
        if button:
            cell = button.index
            row = cell[0]
            id = self.dataModel.item(row, 0).text()  # 编号
            factoryId = self.dataModel.item(row, 9).text()  # 工厂编号
            factoryName = self.dataModel.item(row, 2).text()  # 工厂名称
            self.summaryForm = SummaryForm(self, int(id), int(factoryId), factoryName)
            self.summaryForm.show()

    #  查看，继承父类
    def view_click(self):
        print('view')
        button = self.sender()
        if button:
            cell = button.index
            row = cell[0]
            weld_version_id = 0
            paint_version_id = 0
            summary_version_id = 0
            if self.dataModel.item(row, 6).text() != 'None':
                weld_version_id = self.dataModel.item(row, 6).text()
            if self.dataModel.item(row, 7).text() != 'None':
                paint_version_id = self.dataModel.item(row, 7).text()
            if self.dataModel.item(row, 8).text() != 'None':
                summary_version_id = self.dataModel.item(row, 8).text()
            title = self.dataModel.item(row, 1).text()
            self.dialog = RequireSummaryDetailList(title, int(weld_version_id), int(paint_version_id),
                                                   int(summary_version_id))
            self.dialog.show()

    # 删除，继承父类
    def del_click(self):
        choice = QMessageBox.question(self, '', '是否删除当前数据?', QMessageBox.Yes | QMessageBox.No)  # 1
        if choice == QMessageBox.Yes:  # 2
            button = self.sender()
            if button:
                cell = button.index
                row = cell[0]
                id = self.dataModel.item(row, 0).text()
                model = RequireSummaryModel()
                model.id = int(id)
                delete(model)
                self.refresh()
        elif choice == QMessageBox.No:  # 4
            pass

    # 下载，继承父类
    def download_click(self):
        button = self.sender()
        if button:
            cell = button.index
            row = cell[0]
            id = self.dataModel.item(row, 0).text()

            '''
            选择路径
            '''
            file_name = "零件汇总需求表"
            fileName, filetype = QFileDialog.getSaveFileName(self,
                                                             "选取目录",
                                                             self.cwd + '/' + file_name,  # 起始路径
                                                             "xlsx(*.xlsx)")  # 设置文件扩展名过滤,用双分号间隔

            if fileName == "":
                return

            '''
            异步下载
            '''
            cal_thread = DownloadThread(id, fileName)
            cal_thread.start()
            messageBox = MessageBox()
            messageBox.warrning("提示", "提交成功，请打开下载日志查看结果！")

"""
异步下载
"""
class DownloadThread(threading.Thread):
    def __init__(self, id, file):
        super(DownloadThread, self).__init__()  # 重构run函数必须写
        self.__id = id
        self.__file = file

    def run(self):
        start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        download_log = DownloadLog(self.__id)
        log_id = download_log.add_log(DownloadType.REQUIRE_SUMMARY.value, self.__file, start_time)

        '''
        查询数据
        '''
        # 获取dbsession
        session = get_session()
        # 查询需求
        require_summary = session.query(RequireSummaryModel).filter(RequireSummaryModel.id == self.__id).first()

        # 拼接查询
        my_query = session.query(RequireDetailsModel, RequireModel, FactoryModel)
        my_query = my_query.join(RequireModel, RequireModel.id == RequireDetailsModel.require_id)
        my_query = my_query.join(FactoryModel, FactoryModel.id == RequireModel.factory_id)
        my_query = my_query.filter(RequireDetailsModel.is_del == 0)
        my_query = my_query.filter(
            or_(
                RequireDetailsModel.require_id == require_summary.weld_version_id,
                RequireDetailsModel.require_id == require_summary.paint_version_id,
                RequireDetailsModel.require_id == require_summary.summary_version_id,
            )
        )
        # 执行查询
        data = my_query.all()
        session.close()

        '''
        导出数据
        '''
        try:
            workbook = openpyxl.Workbook()
            worksheet = workbook.worksheets[0]

            # 写入标题
            worksheet.cell(1, 1, "工厂")
            worksheet.cell(1, 2, "零件名称")
            worksheet.cell(1, 3, "生产线")
            worksheet.cell(1, 4, "零件件号")
            worksheet.cell(1, 5, "到货时间")
            worksheet.cell(1, 6, "数量")
            worksheet.cell(1, 7, "供应商名称")

            if len(data) > 0:
                for i in range(len(data)):
                    if data[i][1].production_line == 1:
                        production_line_name = "焊装"
                    elif data[i][1].production_line == 2:
                        production_line_name = "涂装"
                    else:
                        production_line_name = "总装"

                    worksheet.cell(i + 2, 1, data[i][2].name)
                    worksheet.cell(i + 2, 2, data[i][0].parts_name)
                    worksheet.cell(i + 2, 3, production_line_name)
                    worksheet.cell(i + 2, 4, data[i][0].parts_code)
                    worksheet.cell(i + 2, 5, data[i][0].arrival_time)
                    worksheet.cell(i + 2, 6, data[i][0].quantity)
                    worksheet.cell(i + 2, 7, data[i][0].supplier_name)

            workbook.save(self.__file)
        except Exception as e:
            # 上传失败
            end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            download_log.update_log(log_id, end_time, 2, e)
        else:
            # 上传成功
            end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            download_log.update_log(log_id, end_time, 1)


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    MainWindow = RequireSummaryList()
    MainWindow.show()
    sys.exit(app.exec_())
